package net.oschina.simpleplus.erpc.support;

import java.util.concurrent.ConcurrentHashMap;

import com.google.protobuf.GeneratedMessageV3;

public class ProtobufCache {

	private static ConcurrentHashMap<String, GeneratedMessageV3> caches = new ConcurrentHashMap<>();
	
	public static GeneratedMessageV3 get(Class<?> cls) throws Exception{
		GeneratedMessageV3 val = caches.get(cls.getName());
		if(val == null){
			synchronized (ProtobufCache.class) {
				val = caches.get(cls.getName());
				if(val == null){
					val = (GeneratedMessageV3) cls.getMethod("getDefaultInstance", null)
							.invoke(null, null);
					caches.put(cls.getName(), val);
				}
			}
		}
		return val;
	}
	
	public static GeneratedMessageV3 merge(Class<?> cls, byte[] data) throws Exception{
		GeneratedMessageV3 proto = get(cls);
	    return (GeneratedMessageV3) proto.getDefaultInstanceForType().newBuilderForType()
                .mergeFrom(data).build();
	}
}
